package com.atguigu.gulimall.product.service.impl;

import com.atguigu.common.to.SkuReductionTo;
import com.atguigu.common.to.SpuBoundTo;
import com.atguigu.common.to.es.SkuEsModel;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.product.ProductConstant;
import com.atguigu.gulimall.product.entity.*;
import com.atguigu.gulimall.product.feign.CouponFeignService;
import com.atguigu.gulimall.product.feign.SearchFeignService;
import com.atguigu.gulimall.product.feign.WareFeignService;
import com.atguigu.gulimall.product.service.*;
import com.atguigu.gulimall.product.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.product.dao.SpuInfoDao;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;


@Service("spuInfoService")
@Slf4j
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Autowired
    SpuInfoDescService spuInfoDescService;
    @Autowired
    SpuImagesService imagesService;
    @Autowired
    AttrService attrService;
    @Autowired
    ProductAttrValueService attrValueService;
    @Autowired
    SkuInfoService skuInfoService;
    @Autowired
    SkuImagesService skuImagesService;
    @Autowired
    SkuSaleAttrValueService skuSaleAttrValueService;
    @Autowired
    CouponFeignService couponFeignService;
    @Autowired
    BrandService brandService;
    @Autowired
    CategoryService categoryService;
    @Autowired
    WareFeignService wareFeignService;
    @Autowired
    SearchFeignService searchFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * // todo 高级部分完善
     * // todo 发布商品
     *
     * @param vo
     */
    @Transactional
    @Override
    public void saveSpuInfo(SpuSaveVo vo) {

        //todo 1、保存spu基本信息 pms_spu_info
        SpuInfoEntity infoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(vo, infoEntity);
        infoEntity.setCreateTime(new Date());
        infoEntity.setUpdateTime(new Date());
        this.saveBaseSpuInfo(infoEntity);

        //todo 2、保存Spu的描述图片 pms_spu_info_desc
        List<String> descripts = vo.getDecript();
        SpuInfoDescEntity descEntity = new SpuInfoDescEntity();
        descEntity.setSpuId(infoEntity.getId());
        if (!CollectionUtils.isEmpty(descripts)) {
            // String.join(",", descripts):用来把字符串数组或集合，拼接成一个字符串
            descEntity.setDecript(String.join(",", descripts));
        }
        spuInfoDescService.saveSpuInfoDesc(descEntity);

        //todo 3、保存spu的图片集 pms_spu_images
        List<String> images = vo.getImages();
        imagesService.saveImages(infoEntity.getId(), images);

        //todo 4、保存spu的规格参数;pms_product_attr_value
        List<BaseAttrs> baseAttrs = vo.getBaseAttrs();
        List<ProductAttrValueEntity> collect = baseAttrs.stream()
                .map(attr -> {
                    ProductAttrValueEntity valueEntity = new ProductAttrValueEntity();
                    valueEntity.setAttrId(attr.getAttrId());
                    AttrEntity getById = attrService.getById(attr.getAttrId());
                    valueEntity.setAttrName(getById.getAttrName());
                    valueEntity.setAttrValue(attr.getAttrValues());
                    valueEntity.setQuickShow(attr.getShowDesc());
                    valueEntity.setSpuId(infoEntity.getId());
                    return valueEntity;
                }).collect(Collectors.toList());
        attrValueService.saveProductAttr(collect);

        //todo 5、保存spu的积分信息；gulimall_sms->sms_spu_bounds
        Bounds bounds = vo.getBounds();
        SpuBoundTo spuBoundTo = new SpuBoundTo();
        BeanUtils.copyProperties(bounds, spuBoundTo);
        spuBoundTo.setSpuId(infoEntity.getId());
        R r = couponFeignService.saveSpuBounds(spuBoundTo);
        if (r.getCode() != 0) {
            log.error("远程保存spu积分信息失败");
        }

        //todo 5、保存当前spu对应的所有sku信息；
        //5.1）、sku的基本信息；pms_sku_info
        List<Skus> skus = vo.getSkus();
        if (!CollectionUtils.isEmpty(skus)) {
            skus.forEach(sku -> {
                String defaultImg = "";
                if (!CollectionUtils.isEmpty(sku.getImages())) {
                    for (Images image : sku.getImages()) {
                        // 默认图片
                        if (image.getDefaultImg() == 1) {
                            defaultImg = image.getImgUrl();
                        }
                    }
                }
                //    private String skuName;
                //    private BigDecimal price;
                //    private String skuTitle;
                //    private String skuSubtitle;
                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
                BeanUtils.copyProperties(sku, skuInfoEntity);
                skuInfoEntity.setBrandId(infoEntity.getBrandId());
                skuInfoEntity.setCatalogId(infoEntity.getCatalogId());
                skuInfoEntity.setSaleCount(0L);  // 销量
                //
                // 如：Oppo R17（三种颜色：流光蓝、霓光紫、霓光渐变色）和（两种配置：8G+128G、6G+128G）。
                //
                //即:Oppo R17有一个SPU、6种SKU。
                skuInfoEntity.setSpuId(infoEntity.getId());
                skuInfoEntity.setSkuDefaultImg(defaultImg);
                skuInfoService.saveSkuInfo(skuInfoEntity);

                //5.2）、sku的图片信息；pms_sku_image
                Long skuId = skuInfoEntity.getSkuId();
                List<SkuImagesEntity> imagesEntities = sku.getImages().stream()
                        .map(img -> {
                            SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                            skuImagesEntity.setSkuId(skuId);
                            skuImagesEntity.setImgUrl(img.getImgUrl());
                            skuImagesEntity.setDefaultImg(img.getDefaultImg());
                            return skuImagesEntity;

                            //todo 过滤掉没有图片路径的无需保存
                        }).filter(entity -> {
                            //返回true就是需要，false就是剔除
                            return !StringUtils.isEmpty(entity.getImgUrl());
                        }).collect(Collectors.toList());
                skuImagesService.saveBatch(imagesEntities);

                //5.3）、sku的销售属性信息：pms_sku_sale_attr_value
                List<Attr> attr = sku.getAttr();
                List<SkuSaleAttrValueEntity> skuSaleAttrValueEntities = attr.stream()
                        .map(attrVal -> {
                            SkuSaleAttrValueEntity attrValueEntity = new SkuSaleAttrValueEntity();
                            BeanUtils.copyProperties(attrVal, attrValueEntity);
                            attrValueEntity.setSkuId(skuId);
                            return attrValueEntity;
                        }).collect(Collectors.toList());
                skuSaleAttrValueService.saveBatch(skuSaleAttrValueEntities);

                //5.4）、sku的优惠、满减等信息；gulimall_sms -> sms_sku_ladder\sms_sku_full_reduction\sms_member_price
                SkuReductionTo skuReductionTo = new SkuReductionTo();
                BeanUtils.copyProperties(sku, skuReductionTo);
                skuReductionTo.setSkuId(skuId);
                if (skuReductionTo.getFullCount() > 0 || skuReductionTo.getFullPrice().compareTo(new BigDecimal("0")) == 1) {
                    R r1 = couponFeignService.saveSkuReduction(skuReductionTo);
                    if (r1.getCode() != 0) {
                        log.error("远程保存sku优惠信息失败");
                    }
                }
            });
        }
    }

    /**
     * 保存spu的基本信息 pms_spu_info
     *
     * @param infoEntity
     */
    @Override
    public void saveBaseSpuInfo(SpuInfoEntity infoEntity) {
        this.baseMapper.insert(infoEntity);
    }

    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {

        QueryWrapper<SpuInfoEntity> wrapper = new QueryWrapper<>();

        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)) {
            wrapper.and((w) -> {
                w.eq("id", key).or().like("spu_name", key);
            });
        }
        // status=1 and (id=1 or spu_name like xxx)
        String status = (String) params.get("status");
        if (!StringUtils.isEmpty(status)) {
            wrapper.eq("publish_status", status);
        }

        String brandId = (String) params.get("brandId");
        if (!StringUtils.isEmpty(brandId) && !"0".equalsIgnoreCase(brandId)) {
            wrapper.eq("brand_id", brandId);
        }

        String catelogId = (String) params.get("catelogId");
        if (!StringUtils.isEmpty(catelogId) && !"0".equalsIgnoreCase(catelogId)) {
            wrapper.eq("catalog_id", catelogId);
        }

        /**
         * status: 2
         * key:
         * brandId: 9
         * catelogId: 225
         */

        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params), wrapper
        );
        return new PageUtils(page);
    }

    /**
     * 商品上架功能
     * 1、修改商品的状态
     * 2、将商品的有效数据保存到es中
     *
     * @param spuId
     */
    @Transactional
    @Override
    public void spuInfoUp(Long spuId) {

        // 组装数据
        List<SkuEsModel> skuEsModelList = this.skuEsModelList(spuId);

        // 保存到ES中(远程调用gulinall-search服务)
        R r = searchFeignService.productUp(skuEsModelList);

        // 远程调用保存es数据成功
        if (r.getCode() == 0) {
            // 修改上架状态
            SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
            spuInfoEntity.setId(spuId);
            spuInfoEntity.setPublishStatus(ProductConstant.PublishStatus.SPU_UP.getCode());
            spuInfoEntity.setUpdateTime(new Date());
            this.updateById(spuInfoEntity);
        } else {
            // 远程调用失败，
            // todo 重复调用的问题，接口幂等性：重试机制
        }
    }

    /**
     * 封装数据（SkuEsModel）
     *
     * @param spuId
     * @return
     */
    private List<SkuEsModel> skuEsModelList(Long spuId) {
        QueryWrapper<SkuInfoEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("spu_id", spuId);
        List<SkuInfoEntity> skuInfoEntityList = skuInfoService.list(queryWrapper);
        List<SkuEsModel> skuEsModelList = skuInfoEntityList.stream()
                // todo peek和map的的区别：peek是消费类型，map是函数类型
                .peek(
                        skuInfoEntity -> log.info(skuInfoEntity.toString())
                )
                .map(sku -> {
                    // 封装sku信息
                    SkuEsModel skuEsModel = new SkuEsModel();
                    BeanUtils.copyProperties(sku, skuEsModel);
                    skuEsModel.setSkuPrice(sku.getPrice());
                    skuEsModel.setSkuImg(sku.getSkuDefaultImg());

                    // 封装分类和品牌信息
                    BrandEntity brand = brandService.getById(sku.getBrandId());
                    skuEsModel.setBrandName(brand.getName());
                    skuEsModel.setBrandImg(brand.getLogo());
                    CategoryEntity category = categoryService.getById(sku.getCatalogId());
                    skuEsModel.setCatalogName(category.getName());

                    // todo 封装规格参数attrs,并且是可以显示的规格参数
                    List<ProductAttrValueEntity> productAttrValueEntities = attrValueService.baseAttrlistforspu(spuId);
                    // 查询可以显示的规格参数
                    List<Long> attrIds = productAttrValueEntities.stream()
                            .map(ProductAttrValueEntity::getAttrId).collect(Collectors.toList());

                    // todo 封装是否存在库存的信息
                    // 1、远程调用库存服务查询
                    List<SkuHasStockVo> skusHasStockList = null;
                    Map<Long, Boolean> stockMap = null;
                    try {
                        Long[] attrIdsArrays = attrIds.toArray(new Long[0]);
                        skusHasStockList = wareFeignService.getSkusHasStock(attrIdsArrays);
                        // 将是否存在库存的VO集合转换成Map
                        stockMap = skusHasStockList.stream()
                                .collect(Collectors.toMap(SkuHasStockVo::getSkuId, SkuHasStockVo::isHasStock));
                    } catch (Exception e) {
                        e.printStackTrace();
                        log.error("远程调用gulimall-ware服务失败", e);
                    }

                    // 如果服务存在异常，默认认为是有库存的
                    if (null == stockMap) {
                        skuEsModel.setHasStock(true);
                    }
                    // 2、赋值是否存在库存
                    skuEsModel.setHasStock(stockMap.get(sku.getSkuId()));

                    // todo 封装热度评分信息,
                    skuEsModel.setHotScore(0L);

                    // 查询可以显示的规格参数
                    QueryWrapper<AttrEntity> attrQueryWrapper = new QueryWrapper<>();
                    attrQueryWrapper.in("attr_id", attrIds);
                    attrQueryWrapper.eq("catelog_id", sku.getCatalogId());
                    List<AttrEntity> attrEntities = attrService.list(attrQueryWrapper);

                    // 查询出可显示的规格属性
                    List<Long> attrIdsIsShow = attrEntities.stream()
                            .filter(attr -> {
                                return attr.getShowDesc().equals(1);
                            })
                            .map(AttrEntity::getAttrId)
                            .collect(Collectors.toList());

                    // 过滤出可以显示的规格属性
                    List<SkuEsModel.Attrs> collect = attrEntities.stream()
                            .filter(sku1 -> {
                                return attrIdsIsShow.contains(sku1.getAttrId());
                            })
                            .map(sku2 -> {
                                SkuEsModel.Attrs attrs = new SkuEsModel.Attrs();
                                BeanUtils.copyProperties(sku2, attrs);
                                return attrs;
                            }).collect(Collectors.toList());
                    skuEsModel.setAttrs(collect);

                    return skuEsModel;
                }).collect(Collectors.toList());

        return skuEsModelList;
    }
}